import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useRef, forwardRef, useImperativeHandle, useEffect, } from "react";
import { getTplList, draftDirectoryTree } from "./DraftApi";
import DevPopup from "~/public/cpas-ui//components-ui/express-components/DevPopup/index";
import { TreeList } from "devextreme-react";
import { message } from "antd";
import { Radio, Modal } from "antd";
import { Input } from "antd";
import { newPhase } from "./DraftApi";
//   import { useModel } from "umi";
import { getPhaseTreeUpdate } from "./DraftApi";
/**
 * ## 基于本地数据库，获取数据本地数据进行功能演示。
 * ~~~js
 * import LogicPopup  from 'sright-ui'
 * ~~~
 */
export const LogicPopup = forwardRef((props, ref) => {
    // const { initialState } = useModel('@@initialState');
    // const { zcbfid, dbname, sjxmbh } = initialState?.curPart;
    // const { username, usercode } = initialState?.curUser ;
    const [visible, setVisible] = useState(false);
    const [treeData, setTreeData] = useState([]);
    const [tplList, setTplList] = useState([]);
    const [defTplName, setDefTplName] = useState("");
    const [rootValue, setRootValue] = useState("");
    const [DBname, setDBname] = useState("");
    const [ZCbfid, setZCbfid] = useState("");
    const diaParams = useRef();
    const diaParamsData = useRef();
    const paperTreeViewRef = useRef(null);
    const DraftTreeNoteName = useRef(null); // 输入阶段名字
    const [open, setOpen] = useState(false);
    const [isSameLevel, setIsSameLevel] = useState(1);
    useEffect(() => {
        const DBnames = window.sessionStorage.electronParams
            ? JSON.parse(window.sessionStorage.electronParams)?.params?.sjxmbh
            : "FI-2017-00001";
        setDBname(DBnames);
        const ZCbfids = window.sessionStorage.electronParams
            ? JSON.parse(window.sessionStorage.electronParams)?.params?.ZcbfID
            : "FI-2017-00001";
        setZCbfid(ZCbfids);
    }, []);
    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: async (params) => {
            console.log(params, "params");
            diaParams.current = params;
            setVisible(true);
            //   templateTree(diaParams.current?.dbname, 2020).then((v) => {
            //     setTreeData(v);
            //   });
        },
        close: async (params) => {
            console.log(params, "params");
            diaParams.current = params;
            setVisible(false);
            // templateTree(diaParams.current?.dbname, 2020).then((v) => {
            //   setTreeData(v);
            // });
        },
    }));
    const mode = () => {
        return (diaParams.current?.mode === "single" ||
            diaParams.current?.mode === "" ||
            diaParams.current?.mode === undefined);
    };
    const onChange = (e) => {
        console.log("radio checked", e.target.value);
        setIsSameLevel(e.target.value);
    };
    /**
     * 输入框 on
     */
    const InputDraftName = (e) => {
        console.log("radio checked", e.target.value);
        DraftTreeNoteName.current = e.target.value;
    };
    /**
     *
     * @param item 插入附注到底稿子集
     * @returns
     */
    const insertDraftNote = async (item) => {
        console.log("radio checked", item);
        let DraftTreeNoteNameTemp = item.text; // as jdmc 要追加的阶段名字
        if (isSameLevel === 2) {
            // 获取父阶段的名字
            const r = await newPhase(DraftTreeNoteName.current, rootValue, item.pid === rootValue ? null : item?.pid.replaceAll(rootValue, ""), diaParams.current.zcbfid, diaParams.current.username, diaParams.current.dbname);
            if (r.data.length && r.data[0].code === "009") {
                return message.error(`添加的阶段${r.data[0].msg},追加底稿失败`);
            }
            DraftTreeNoteNameTemp = DraftTreeNoteName.current;
        }
        //@ts-ignore
        const res = await getPhaseTreeUpdate(diaParams.current.username, rootValue, DraftTreeNoteNameTemp, diaParams.current.sjxmbh, diaParams.current.zcbfid, diaParams.current.dbname, 
        //@ts-ignore
        [`${window?.main?.mainObject?.getAppPath() ?? ""}/Temp/Excel附注.xlsx`]);
        // debugger
        if (res.success) {
            if (res.data.length && res.data[0].code !== "200") {
                return message.error(`添加的底稿${res.data[0].msg},追加底稿失败`);
            }
            else {
                diaParams.current.okCallback();
                message.info(`追加成功`);
            }
        }
        setVisible(false);
        setTimeout(() => {
            setOpen(false);
        }, 100);
    };
    return (_jsx("div", { children: _jsx(DevPopup.Logic, { ref: ref, width: 520, height: 500, visible: visible, title: diaParams.current?.title, toolbarDisplay: diaParams.current?.toolbarDisplay, okCallbackShow: false, onShown: () => {
                if (treeData.length > 0)
                    return;
                getTplList(diaParams.current.dbname).then((v) => {
                    console.log(v, "v1111");
                    if (!v && !v.length) {
                        return message.error("请选择要导出的底稿文件");
                    }
                    setTplList(v);
                });
            }, onCancel: () => {
                setTimeout(() => {
                    setVisible(false);
                }, 200);
            }, onHiding: () => {
                setVisible(false);
                diaParams.current.okCallback();
                paperTreeViewRef.current?.instance.clearFilter("search");
                setDefTplName("");
                setTreeData([]);
            }, children: () => {
                return (_jsxs(_Fragment, { children: [_jsxs(Modal, { title: "\u8BBE\u7F6E\u5B50\u7EA7\u6216\u8005\u540C\u7EA7", centered: true, mask: false, destroyOnClose: true, open: open, onOk: () => insertDraftNote(diaParamsData.current), onCancel: () => setOpen(false), width: 500, maskClosable: false, zIndex: 10000, children: [_jsxs(Radio.Group, { onChange: onChange, value: isSameLevel, children: [_jsx(Radio, { value: 1, children: "\u8BBE\u7F6E\u5B50\u7EA7" }), _jsx(Radio, { value: 2, children: "\u8BBE\u7F6E\u540C\u7EA7" })] }), _jsx("br", {}), isSameLevel === 2 ? (_jsx(Input, { size: "large", onChange: InputDraftName, placeholder: "\u8F93\u5165\u9636\u6BB5\u540D\u5B57" })) : ("")] }), _jsx(TreeList, { className: "PaperTreeList", dataSource: treeData, keyExpr: "id", parentIdExpr: "pid", rootValue: rootValue, showRowLines: false, showBorders: false, columnAutoWidth: true, ref: paperTreeViewRef, onCellDblClick: (e) => {
                                console.log(e);
                                // 弹窗选择子级或者同级
                                setTimeout(() => {
                                    setOpen(true);
                                }, 500);
                                diaParamsData.current = e.data;
                            }, 
                            // onSelectionChanged={(e:any) => {
                            //   // const res =
                            //   //   e.selectedRowsData;
                            //   // if (res.length > 0) diaParamsData.current = res;
                            //   console.log(e.selectedRowsData,"e.selectedRowsData");
                            // }}
                            width: "100%", height: "100%", searchPanel: {
                                visible: true,
                                width: 180,
                                placeholder: "",
                            }, toolbar: {
                                items: [
                                    {
                                        widget: "dxSelectBox",
                                        location: "before",
                                        options: {
                                            width: 280,
                                            value: `${defTplName}`,
                                            dataSource: tplList,
                                            searchEnabled: true,
                                            searchMode: "contains",
                                            searchExpr: "text",
                                            valueExpr: "id",
                                            displayExpr: "text",
                                            onValueChanged: (e) => {
                                                // debugger
                                                // setSourcePath(e.value);
                                                setDefTplName(e.value);
                                                setRootValue(e.value);
                                                draftDirectoryTree({
                                                    dbname: diaParams.current.dbname,
                                                    zcbfid: diaParams.current.zcbfid,
                                                }).then((v) => {
                                                    setTreeData(v
                                                        .filter((a) => a.dgnd === e.value)
                                                        .map((a) => {
                                                        return a;
                                                    }));
                                                });
                                            },
                                        },
                                    },
                                    {
                                        name: "searchPanel",
                                        location: "after",
                                    },
                                ],
                            }, selection: {
                                recursive: true,
                                mode: mode() ? "single" : "multiple",
                            }, columns: [
                                {
                                    dataField: "text",
                                    caption: "阶段名称",
                                },
                            ] })] }));
            } }) }));
});
export default LogicPopup;
